signed and unsigned
The most important thing that we need to keep in mind is, both signed and unsigned type modifiers are applied only to data types of the integer family i.e. char and int.
Signed type modifier in C:
For an int data type, if we don't mention type modifier, By default it will be considered as a signed type modifier.
- The variable with signed type modifier is capable of storing both positive and negative values.
- A variable with a 32-bit integer data type, 1-bit (Most significant bit) is reserved for sign & remaining 31-bits are used for data.
- If the most significant bit contains '0' then it means that the variable contains a positive value & 1 specifies that the variable contains a negative value.
Formulae to calculate the range of any datatype with signed type modifier:
- The range of the data type with signed type modifier is
-2(N-1) to +2(N-1)-1
. Here N is the no of bits allocated for the data type. - 'N' value can be calculated by using N = 8 x Size of the data type.
Unsigned type modifier in C:
For a char data type, if we don't mention type modifier, By default it will be considered as unsigned type modifier.
- The variable with unsigned type modifier is capable of storing only positive values.
- No sign bit is reserved for variables declared with unsigned type modifier. All the 32 bits contain data.
Formulae to calculate the range of any data type with unsigned type modifier:
- The range of the data type with unsigned type modifier is
0 to +2(N)-1
. Here N is the no of bits allocated for the data type. - 'N' value can be calculated by using formulae N = 8 x Size of the data type.
Explanation:
- '%u' is a format specifier used in printf to specify, the variable is of type unsigned integer.
- In the above example, the variable 'a' is capable of holding both positive and negative values because 1-bit is reserved for the sign and variable 'b' is capable of storing only positive values.
- By default, int uses signed type modifier and char uses unsigned type modifier.
Video Reference:
© 2020 Pragimtech. All Rights Reserved.